import * as PIXI from 'pixi.js';
import parsedRes from './utils/resource';
import { gsap } from 'gsap';

let type = 'WebGL';
if(!PIXI.utils.isWebGLSupported()) {
    type = 'Canvas';
}
PIXI.utils.sayHello(type);

let width, height, resolution;
const stage = document.querySelector('#app');
width = stage.clientWidth;
height = stage.clientHeight;
const app = new PIXI.Application({
    width,
    height,
    antalias: true,
    backgroundAlpha: 0
});
resolution = width / 828;
app.stage.scale.set(resolution);
stage.appendChild(app.view);

let sprites = {}, conts = {};

const { intro, index } = parsedRes;

const welcome = [...intro, ...index];

app.loader.add(welcome).load((loader, resources) => {
    welcome.forEach(ele => {
        addSprite(ele, resources);
    });
    addListeners();
});

function addSprite(ele, resources) {
    const sprite = new PIXI.Sprite(resources[ele.name].texture);
    sprite.pivot.x = sprite.width / 2;
    sprite.pivot.y = sprite.height / 2;
    sprite.position.x = ele.position ? ele.position.x + sprite.width / 2 : sprite.width / 2;
    sprite.position.y = ele.position ? ele.position.y + sprite.height / 2 : sprite.height / 2;
    let interactive = ele.interactive || false;
    sprite.interactive = interactive;
    if(!conts[ele.cont]) {
        const container = new PIXI.Container();
        app.stage.addChild(container);
        conts[ele.cont] = container;
    };
    conts[ele.cont].addChild(sprite);
    sprites[ele.name] = sprite;
}

function addListeners() {
    sprites['index_start'].on('tap', skipIntro);
}

function skipIntro() {
    gsap.to(conts['index'], { alpha: 0 });
}